export class Timer {
  constructor() {
    this.setTimeoutId = null;
    this.setIntervalId = null;
    this.isRunning = false;
    this.experienceTime = 0;
    // 默认间隔时间1s
    this.interval = 1000;
  }

  start(duration, intervalCallback) {
    if (this.isRunning) {
      console.log("计时器正在工作");
      return;
    }
    this.isRunning = true;
    this.experienceTime = 0;
    console.log("计时开始");
    this.setIntervalId = setInterval(() => {
      this.experienceTime++;
      if (intervalCallback && typeof intervalCallback === "function") {
        // 将经历的时间传递出去
        intervalCallback(this.experienceTime);
      }
    }, this.interval);
    this.setTimeoutId = setTimeout(() => {
      this.stop();
    }, duration * 1000);
  }

  stop() {
    if (!this.isRunning) {
      console.log("计时器正在工作");
      return;
    }
    console.log("计时结束");
    clearInterval(this.setIntervalId);
    clearTimeout(this.setTimeoutId);
    this.isRunning = false;
    this.setTimeoutId = null;
    this.setIntervalId = null;
  }
}